<?php
/*
 *   Pmail easy way to send emails
 *   Copyright (C) 2009  Felipe Theodoro Gonçalves (www.ftgoncalves.com)
 *
 *   This program is free software: you can redistribute it and/or modify
 *	 it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
class MailsController extends PmailAppController {

	public $uses = array('Pmail.Config', 'Pmail.Mail', 'Pmail.Layer', 'Pmail.Group', 'Pmail.Member', 'Pmail.Report', 'Pmail.Label');

	public $components = array('Session', 'Email');

	// Atributo para controle de email enviados com sucesso
	private $email_sucesso = 0;

	// Atributo para controle de email enviados com erro
	private $email_erro = 0;

	private $config = array();

	private $smtp = null;

	public $paginate = array(
		'limit' => 50,
		'order' => array(
			'created' => 'DESC'
		)
	);

	public function beforeFilter(){

		$this->set('page', 'mails');

	}

	/**
	 * Envia email
	 *
	 */
	public function index(){

		// Processo de envio de email
		if(isset($this->data['Pmail'])){

			$this->arrangeMailToSend($this->data);

		}

		// get mails
		$emails = $this->Mail->find('list', array(
			'fields' => array('Mail.id', 'Mail.identifier')
		));

		$this->set('emails', $emails);

		// get groups
		$groups = $this->Group->find('list', array(
			'fields' => array('Group.id', 'Group.name')
		));

		$this->set('groups', $groups);
		$this->render();

	}

	/**
	 * Configure and send a e-mail
	 *
	 * @param $data = array()
	 * @param $automatic = false
	 */
	private function arrangeMailToSend($data = array(), $automatic = false){


		$layer = array();

		//$more_contacts = null;

		// get contatos
		foreach($data['Pmail']['to'] as $group){

			$contacts[$group] = $this->Member->find('all', array(
				'conditions' => array('Member.pmail_groups_id' => $group),
				'fields' => array('Member.id', 'Member.name', 'Member.email')
			));

		}

		// Envio para contatos extras
		//$more_contacts = explode(',', $data['Pmail']['emails']);

		// get mail
		$email = $this->Mail->find('first', array(
			'conditions' => array('Mail.id' => $data['Pmail']['email'])
		));

		// Caso não exista um layer
		if(empty($email['Mail']['layer'])){

			$layer['Layer']['html'] = '[content]';

		}else{

			$layer = $this->Layer->find('first', array(
				'conditions' => array('Layer.id' => $email['Mail']['layer']),
				'fields' => array('Layer.html')
			));

		}

		// Config subject
		if(empty($email['Mail']['subject'])){

			$subject = '[Pmail]';

		}else{

			$subject = $email['Mail']['subject'];

		}

		// config from
		if(empty($email['Mail']['from'])){

			// Set default from
			$this->Config->id = 1;
			$from = $this->Config->read();
			$from = $from['Config']['from'];

		}else{

			$from = $email['Mail']['from'];

		}

		// Config email pega tudo
		$this->Config->id = 1;
		$this->config = $email_handle_everything = $this->Config->read();

		if(empty($email_handle_everything['Config']['email_handle_everything'])){

			$email_handle_everything = null;

		}else{

			$email_handle_everything = array($email_handle_everything['Config']['email_handle_everything']);

		}

		// Set SMTP
		if(!empty($this->config['Config']['smtp_host'])){

			$this->smtp = array(
				'port' => $this->config['Config']['smtp_port'],
				'timeout' => $this->config['Config']['smtp_timeout'],
				'host' => $this->config['Config']['smtp_host'],
				'username' => $this->config['Config']['smtp_login'],
				'password' => $this->config['Config']['smtp_password'],
			);

		}

		// The data of content
		$message = str_replace('[content]', $email['Mail']['message'], $layer['Layer']['html']);

		// Verifier the assinature
		if(ereg('\[signature\]', $message)){

			if(empty($email['Mail']['signature'])){

				$message = str_replace('[signature]', $this->config['Config']['signature'], $message);

			}else{

				$message = str_replace('[signature]', $email['Mail']['signature'], $message);

			}

		}

		// Enviando os emails
		foreach($contacts as $aux){

			foreach($aux as $contact){

				// Verifica se existe o marcador [name]
				if(ereg('\[name\]', $message)){

					$message_custon = str_replace('[name]', $contact['Member']['name'], $message);

				}

				// Verifica se existe o marcador [email]
				if(ereg('\[email\]', $message)){

					$message_custon = str_replace('[email]', $contact['Member']['email'], $message_custon);

				}

				//send mail
				$this->send($contact['Member']['email'], $email_handle_everything, $subject, $from, $message_custon, $this->smtp);

			}

		}

		// Save Report
		$report = array(
			'Report' => array(
				'identifier' => $email['Mail']['identifier'],
				'sucesso' => $this->email_sucesso,
				'erro' => $this->email_erro
			)
		);

		$this->Report->set($report);
		$this->Report->save();
		$this->Session->setflash(__d('pmail', $this->email_sucesso . ' emails were sent successfully and ' . $this->email_erro . ' emails does not succeed', true), 'default', array(), 'info');
		$this->redirect('/pmail');

	}

	public function report(){

		$this->set("reports", $this->paginate("Report"));

		$this->render();

	}

	/**
	 * Save and atualiza mail
	 *
	 * @param int $id = null
	 */
	public function save_mail($id = null){

		if($this->data){

			// E-mail text don`t save
			if(!empty($this->data['texte_email'])){

				// Send email
				$this->Session->setFlash(__d('pmail', 'Email sent successfully', true), 'default', array(), 'sucesso');
				$this->redirect('/pmail/mails/index');

			}else{

				if($id != null){

					$this->Mail->id = $id;

				}

				// Set <br>
				$this->data['Mail']['signature'] = nl2br($this->data['Mail']['signature']);
				$this->Mail->set($this->data);
				$this->Mail->save();

				if($id != null){

					$this->Session->setFlash(__d('pmail', 'Email modificadio successfully', true), 'default', array(), 'sucesso');
					$this->redirect('/pmail/mails/view_mails');

				}else{

					$this->Session->setFlash(__d('pmail', 'Email unless successfully', true), 'default', array(), 'sucesso');
					$this->redirect('/pmail/mails/index');

				}

			}

		}else{

			$this->Session->setFlash(__d('pmail', 'It is necessary to fill in all fields', true), 'default', array(), 'erro');
			$this->redirect('/pmail');

		}

	}

	/**
	 * Compose mail
	 *
	 */
	public function create_email(){

		// get configured
		$config = $this->Config->read(array('signature', 'from'), 1);
		$this->set('signature', $config['Config']['signature']);
		$this->set('from', $config['Config']['from']);

		// get layers
		$layers = $this->Layer->find('list',array(
			'fields' => array('Layer.id', 'Layer.identifier')
		));

		$this->set('layers', $layers);
		$this->render();

	}

	/**
	 * Methodo privado para envio de emails
	 *
	 * @param String $to = null
	 * @param array $bcc = null
	 * @param String $subject = null
	 * @param String $from = null
	 * @param String $message = null
	 * @param array $smtp = null
	 */
	private function send($to = null, $bcc = null, $subject = null, $from = null, $message = null, $smtp = null){

		// Config data mail
		$this->Email->to = $to;

		if(is_array($bcc))
			$this->Email->bcc = $bcc;

		$this->Email->subject = $subject;
		$this->Email->from = $from;
		$this->Email->template = 'pmail_default';
		$this->Email->sendAs = 'html';

		$this->set('message', $message);

		// Verifier smtp mode
		if(is_array($smtp)){

			$this->Email->smtpOptions = $smtp;
			$this->Email->delivery = 'smtp';

		}

		if($this->Email->send()){

			$this->email_sucesso++;

		}else{

			$this->email_erro++;

		}

		$this->Email->reset();

	}

	public function view_mails(){

		$emails = $this->Mail->find('all', array(
			'fields' => array('Mail.id', 'Mail.identifier', 'Mail.created')
		));

		$this->set('emails', $emails);
		$this->render();

	}

	public function delete_email($id = null){

		if($id != null){

			$this->Mail->id = $id;
			$this->Mail->del();
			$this->Session->setFlash(__d('pmail', 'Email deleted successfully', true), 'default', array(), 'sucesso');
			$this->redirect($this->referer());

		}else{

			$this->Session->setFlash(__d('pmail', 'Choose an email to execute this option', true), 'default', array(), 'erro');
			$this->redirect('/pmail/mails/view_mails');

		}

	}

	public function edit_email($id = null){

		if($id != null){

			$mail = $this->Mail->find('all', array(
				'conditions' => 'Mail.id = ' . $id
			));

			$this->data = $mail[0];


			// get layers
			$layers = $this->Layer->find('list',array(
				'fields' => array('Layer.id', 'Layer.identifier')
			));

			$this->set('layers', $layers);
			$this->render('create_email');

		}else{

			$this->Session->setFlash(__d('pmail', 'Choose an email to execute this option', true), 'default', array(), 'erro');
			$this->redirect('/pmail/mails/view_mails');

		}

	}

	public function layer(){

		// set labels
		$labels = $this->Label->find('all', array(
			'fields' => array('Label.name', 'Label.description')
		));

		$this->set('labels', $labels);
		$this->render();

	}

	/**
	 * Methodo responsavel por armazenar os novos layers
	 *
	 */
	public function save_layer($id = null){

		if(isset($this->data)){

			// Para alteração de layer
			if($id)
				$this->Layer->id = $id;

			$this->Layer->set($this->data);
			$this->Layer->save();
			$this->Session->setFlash(__d('pmail', 'Save successfully', true), 'default', array(), 'sucesso');
			$this->redirect('/pmail/mails/index');

		}

		$this->Session->setFlash(__d('pmail', 'Error attempting to execute this option', true), 'default', array(), 'erro');
		$this->redirect('/pmail/mails/index');

	}

	/**
	 * Methodo para visualizar todas os layers criados
	 *
	 */
	public function view_layers(){

		$layers = $this->Layer->find('all');
		$this->set('layers', $layers);
		$this->render();

	}

	/**
	 * Methodo responsavel pela visualização de apenas 1 layer
	 *
	 * @param int $id = null
	 */
	public function view_layer($id = null){

		if($id != null){

			Configure::write('debug', 0);
			$this->layout = 'blank';

			$layer = $this->Layer->find('first', array(
				'conditions' => array(
					'Layer.id' => $id
				),
				'fields' => array(
					'Layer.identifier', 'Layer.html'
				)
			));

			$this->pageTitle = 'layer identifier : ' . $layer['Layer']['identifier'];
			$this->set('layer', $layer);
			$this->render();

		}else{

			$this->Session->setFlash(__d('pmail', 'Error attempting to execute this option', true), 'default', array(), 'erro');
			$this->redirect('/pmail');

		}

	}

	/**
	 * Methodo responsável por deletar os layer
	 *
	 * @param int $id = null
	 */
	public function delete_layer($id = null){

		if($id != null){

			$this->Layer->del($id);
			$this->Session->setFlash(__d('pmail', 'Layout deleted successfully', true), 'default', array(), 'sucesso');
			$this->redirect($this->referer());

		}else{

			$this->Session->setFlash(__d('pmail', 'Error attempting to execute this option', true), 'default', array(), 'erro');
			$this->redirect('/pmail');

		}

	}

	/**
	 * Edição do layer
	 *
	 * @param int $id = null
	 */
	public function edit_layer($id = null){

		if($id != null){

			// set labels
			$labels = $this->Label->find('all', array(
				'fields' => array('Label.name', 'Label.description')
			));

			$this->set('labels', $labels);
			$this->Layer->id = $id;
			$layer = $this->Layer->read();
			$this->data = $layer;
			$this->render('layer');

		}

	}

	/**
	 * Cria os menus automatico
	 *
	 */
	public function menu(){

		$this->layout = 'blank';
		Configure::write('debug', 0);

		$links = array(
			'Send email' => array('plugin' => 'pmail', 'controller' => 'mails', 'action' => 'index'),
			'Create a email' => array('plugin' => 'pmail', 'controller' => 'mails', 'action' => 'create_email'),
			'See emails configured' => array('plugin' => 'pmail', 'controller' => 'mails', 'action' => 'view_mails'),
			'Create a new layout' => array('plugin' => 'pmail', 'controller' => 'mails', 'action' => 'layer'),
			'See layouts configured' => array('plugin' => 'pmail', 'controller' => 'mails', 'action' => 'view_layers')
		);

		$this->set('links', $links);
		$this->render('menu/menu');

	}

}